import {
  login,
  logout,
} from '@/api/user'
import { setToken, getToken, userLocalTool } from '@/libs/util'

export default {
    namespaced: true,
  'state': {
    'userName': userLocalTool.getUserName(),
    'avatorImgPath': userLocalTool.getAvatar(),
    'token': getToken()
  },
  'mutations': {
      setAvatar(state, avatorPath) {
      state.avatorImgPath = avatorPath
      userLocalTool.setAvatar(avatorPath)
    },
    setUserName(state, name) {
      state.userName = name
      userLocalTool.setUserName(name)
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    }
  },
  'actions': {
    // 登录
    handleLogin({ commit }, { userName, password }) {

        const isFake = false;

        if (isFake) {// todo 假登录，可以删除
            return new Promise((resolve, reject) => {
                const data = {
                    token_type  : 'Bear',
                    access_token: '124324',
                    user_info   : {
                        name  : '1341',
                        avatar: '1341'
                    }
                };
                commit('setToken', data.token_type + ' ' + data.access_token)
                commit('setUserName', data.user_info.name)
                commit('setAvatar', data.user_info.avatar)

                resolve()
            });
        }

      return new Promise((resolve, reject) => {
        login({
          userName: userName.trim(),
          password
        }).then(res => {
          // const data = res.data.data
            const data = {
                token_type : 'Bearer',
                access_token : res.data.data.token,
                user_info:{
                    name : userName,
                    avatar : '/favicon.ico'
                }
            };
          commit('setToken', data.token_type + ' ' + data.access_token)
          commit('setUserName', data.user_info.name)
          commit('setAvatar', data.user_info.avatar)

          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
          logout().then(() => {
              commit('setToken', '')
              commit('setUserName', '')
              commit('setAvatar', '')
              resolve()
          });
        // logout(state.token).then(() => {
        
        /*
         * }).catch(err => {
         *   reject(err)
         * })
         */
        /*
         * 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
         * commit('setToken', '')
         * commit('setAccess', [])
         * resolve()
         */
      })
    }

  }
}
